package com.myexam.util;


import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;


public class PageUtil {
	
	public static Page createPage(int everyPage,int totalCount,int currentPage){
		everyPage = getEveryPage(everyPage);
		currentPage = getCurrentPage(currentPage);
		int totalPage = getTotalPage(everyPage, totalCount);
		int beginIndex = getBeginIndex(everyPage, currentPage);
		boolean hasPrePage = getHasPrePage(currentPage);
		boolean hasNextPage = getHasPage(totalPage, currentPage);
		return new Page(everyPage, totalCount, totalPage, currentPage, beginIndex, hasPrePage, hasNextPage);
	}
	
	public static int getEveryPage(int everyPage){
		return everyPage == 0 ? 10 :everyPage;
	}
	
	public static int getCurrentPage(int currentPage){
		return currentPage == 0 ? 1 : currentPage;
	}
	
	public static int getTotalPage(int everyPage,int totalCount){
		int totalPage = 0;
		if(totalCount != 0 && totalCount % everyPage == 0){
			totalPage = totalCount / everyPage;
		}else{
			totalPage = totalCount / everyPage + 1;
		}
		return totalPage;
	}
	
	public static int getBeginIndex(int everyPage,int currentPage){
		return (currentPage - 1)* everyPage;
	}
	
	
	public static boolean getHasPrePage(int currentPage){
		return currentPage == 1 ? false : true;
	}
	
	
	public static boolean getHasPage(int totalPage,int currentPage){
		return totalPage == currentPage || totalPage == 0 ? false : true;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> List<T> getList(Session session,String hql,Page page){
		Query query = session.createQuery(hql);
		query.setMaxResults(page.getEveryPage()).setFirstResult(page.getBeginIndex());
		List<T> list = query.list();
		return list;
	}
	
	
	@SuppressWarnings("unchecked")
	public static <T> List<T> getList(Session session, String hql, int number){
		List<T> list = session.createQuery(hql).setMaxResults(number).list();
		return list;
	}
	
	/*@SuppressWarnings("unchecked")
	public static <T> List<T> getList(String arg,List<T> args){
		List<Subject> subjects = (List<Subject>) args;
		List<Subject> newSubjects = new ArrayList<>();
		
		for(Subject subject : subjects){
			String newTitleString = subject.getSubjectTitle().replace(arg, "<font color='red'>"+arg+"</font>");
			subject.setSubjectTitle(newTitleString);
			newSubjects.add(subject);
		}
		return (List<T>) newSubjects;
	}*/
	
	public static Page getPage(int everyPage, int currentPage){
		Page page = new Page();
		page.setEveryPage(everyPage);
		page.setCurrentPage(currentPage);
		return page;
	}
}
